package com.rainng.coursesystem.repository;

import com.rainng.coursesystem.model.entity.CourseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CourseRepository {

    private final JdbcTemplate jdbcTemplate;

    public CourseRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 获取所有课程
    public List<CourseEntity> findAll() {
        String sql = "SELECT * FROM courses";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CourseEntity.class));
    }

    // 根据 ID 获取课程
    public CourseEntity findById(Integer id) {
        String sql = "SELECT * FROM rc_course, rc_student_course WHERE rc_course.course_id = rc_student_course.sc_course_id and rc_student_course.sc_id = ?";

        CourseEntity course = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            CourseEntity course1 = new CourseEntity();
            // 填充课程ID
            course1.setId(rs.getInt("course_id"));

            // 填充课程名称
            course1.setName(rs.getString("course_name"));

            // 填充教师ID
            course1.setTeacherId(rs.getInt("course_teacher_id"));

            // 填充课程年级
            course1.setGrade(rs.getInt("course_grade"));

            // 填充课程时间
            course1.setTime(rs.getString("course_time"));

            // 填充课程地点
            course1.setLocation(rs.getString("course_location"));

            // 填充学分
            course1.setCredit(rs.getInt("course_credit"));

            // 填充已选人数
            course1.setSelectedCount(rs.getInt("course_selected_count"));

            // 填充课程容量
            course1.setMaxSize(rs.getInt("course_max_size"));

            // 填充考试日期
            course1.setExamDate(rs.getTimestamp("course_exam_date"));  // 使用 rs.getTimestamp() 来映射到 java.util.Date 或 java.sql.Timestamp

            // 填充考试地点
            course1.setExamLocation(rs.getString("course_exam_location"));

            return course1;
        }, id);

        System.out.println(course);
        return course;
    }

    // 删除课程
    public void deleteById(Integer id) {
        String sql = "DELETE FROM courses WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    // 添加课程
    public void save(CourseEntity course) {
        String sql = "INSERT INTO courses (name, teacherId, grade, time, location, credit, selectedCount, maxSize, examDate) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, course.getName(), course.getTeacherId(), course.getGrade(), course.getTime(),
                course.getLocation(), course.getCredit(), course.getSelectedCount(), course.getMaxSize(), course.getExamDate());
    }
}
